﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Text.RegularExpressions;

namespace AliCMS.CollectModule.OleDb
{
    public class Rule : OleDbBase, Dal.IRule
    {
        public int GetInnerIDFromGuid(Guid guid)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Rule.ID, MapType(Alias.Rule.ID)).Value = guid;
            Command.CommandText = "SELECT " + MapColumn(Alias.Rule.InnerID) + " FROM " + MapTable(Alias.Objects.Rule) + " WHERE " + MapColumn(Alias.Rule.ID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return 0;
            else
                return (int)result;
        }
        public Guid GetGuidFromInnerID(object id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Rule.InnerID, MapType(Alias.Rule.InnerID)).Value = id;
            Command.CommandText = "SELECT " + MapColumn(Alias.Rule.ID) + " FROM " + MapTable(Alias.Objects.Rule) + " WHERE " + MapColumn(Alias.Rule.InnerID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return Guid.Empty;
            else
                return (Guid)result;
        }
        public Dictionary<string, object> Get(object id)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            StringBuilder sql = new StringBuilder("SELECT TOP 1");
            sql.Append(" " + MapColumn(Alias.Rule.ID));
            sql.Append("," + MapColumn(Alias.Rule.InnerID));
            sql.Append("," + MapColumn(Alias.Rule.Name, Lang));
            sql.Append("," + MapColumn(Alias.Rule.Config));
            sql.Append("," + MapColumn(Alias.Rule.Description, Lang));
            sql.Append("," + MapColumn(Alias.Rule.Every));
            sql.Append("," + MapColumn(Alias.Rule.StartTime));
            sql.Append("," + MapColumn(Alias.Rule.AutoExport));
            sql.Append("," + MapColumn(Alias.Rule.LastRun));
            sql.Append("," + MapColumn(Alias.Rule.RunTimes));
            sql.Append("," + MapColumn(Alias.Rule.EndTime));
            sql.Append("," + MapColumn(Alias.Rule.LastID));
            sql.Append("," + MapColumn(Alias.Rule.UserAgent));
            sql.Append("," + MapColumn(Alias.Rule.IsDeleted));
            sql.Append("," + MapColumn(Alias.Rule.CreatorID));
            sql.Append("," + MapColumn(Alias.Rule.Creator));
            sql.Append("," + MapColumn(Alias.Rule.CreateTime));
            sql.Append("," + MapColumn(Alias.Rule.UpdatorID));
            sql.Append("," + MapColumn(Alias.Rule.Updator));
            sql.Append("," + MapColumn(Alias.Rule.UpdateTime));
            sql.Append(" FROM " + MapTable(Alias.Objects.Rule));

            if (id is Guid)
            {
                Command.CommandText = sql + " WHERE " + MapColumn(Alias.Rule.ID) + "=?";

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.Rule.ID, MapType(Alias.Rule.ID)).Value = id;
            }
            else
            {
                Command.CommandText = sql + " WHERE " + MapColumn(Alias.Rule.InnerID) + "=?";

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.Rule.InnerID, MapType(Alias.Rule.InnerID)).Value = id;
            }

            DataReader = Command.ExecuteReader();
            if (!DataReader.HasRows)
            {
                DataReader.Close();
                return null;
            }

            DataReader.Read();
            int i = 0;
            result[Alias.Rule.ID] = DataReader[i++];
            result[Alias.Rule.InnerID] = DataReader[i++];
            result[Alias.Rule.Name] = DataReader[i++];
            result[Alias.Rule.Config] = DataReader[i++];
            result[Alias.Rule.Description] = DataReader[i++];
            result[Alias.Rule.Every] = DataReader[i++];
            result[Alias.Rule.StartTime] = DataReader[i++];
            result[Alias.Rule.AutoExport] = DataReader[i++];
            result[Alias.Rule.LastRun] = DataReader[i++];
            result[Alias.Rule.RunTimes] = DataReader[i++];
            result[Alias.Rule.EndTime] = DataReader[i++];
            result[Alias.Rule.LastID] = DataReader[i++];
            result[Alias.Rule.UserAgent] = DataReader[i++];
            result[Alias.Rule.IsDeleted] = DataReader[i++];
            result[Alias.Rule.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Rule.Creator] = DataReader[i++];
            result[Alias.Rule.CreateTime] = DataReader[i++];
            result[Alias.Rule.UpdatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Rule.Updator] = DataReader[i++];
            result[Alias.Rule.UpdateTime] = DataReader[i++];
            DataReader.Close();

            return result;
        }
        public void Add(Dictionary<string, object> item)
        {
            #region 设置RowLang
            item.Add(Alias.Rule.RowLang, "|" + Lang + "|");
            #endregion

            StringBuilder names = new StringBuilder();
            StringBuilder values = new StringBuilder();

            Command.Parameters.Clear();
            PrepareParameters(names, values, item);

            Command.CommandText = "INSERT INTO " + MapTable(Alias.Objects.Rule) + "(" + names + ") VALUES(" + values + ")";
            Command.ExecuteNonQuery();
        }
        public void Modify(int id, Dictionary<string, object> changes)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Rule.InnerID, MapType(Alias.Rule.InnerID)).Value = id;

            #region 检查并设置RowLang
            Command.CommandText = "SELECT " + MapColumn(Alias.Rule.RowLang) + " FROM " + MapTable(Alias.Objects.Rule) + " WHERE " + MapColumn(Alias.Rule.InnerID) + "=?";
            string rowLang = Command.ExecuteScalar().ToString();
            if (!rowLang.Contains("|" + Lang + "|"))
                changes.Add(Alias.Rule.RowLang, rowLang + Lang + "|");
            #endregion

            StringBuilder sql = new StringBuilder("UPDATE " + MapTable(Alias.Objects.Rule) + " SET ");
            Command.Parameters.Clear();
            PrepareParameters(sql, changes);
            Command.Parameters.Add("@" + Alias.Rule.InnerID, MapType(Alias.Rule.InnerID)).Value = id;

            sql.Append(" WHERE " + MapColumn(Alias.Rule.InnerID) + "=?");

            #region HasSelfLimitation
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null && Convert.ToBoolean(user["HasSelfLimitation"]))
                {
                    sql.Append(" AND " + MapColumn(Alias.Rule.CreatorID) + "=?");
                    Command.Parameters.Add("@" + Alias.Rule.CreatorID, MapType(Alias.Rule.CreatorID)).Value = new Guid(user["ID"]);
                }
            }
            #endregion

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public void Delete(int id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Rule.InnerID, MapType(Alias.Rule.InnerID)).Value = id;

            StringBuilder sql = new StringBuilder("DELETE FROM " + MapTable(Alias.Objects.Rule) + " WHERE " + MapColumn(Alias.Rule.InnerID) + "=?");

            #region HasSelfLimitation
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null && Convert.ToBoolean(user["HasSelfLimitation"]))
                {
                    sql.Append(" AND " + MapColumn(Alias.Rule.CreatorID) + "=?");
                    Command.Parameters.Add("@" + Alias.Rule.CreatorID, MapType(Alias.Rule.CreatorID)).Value = new Guid(user["ID"]);
                }
            }
            #endregion

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public DataTable List(int page, int pageSize, string condition, string sort)
        {
            DataTable result = new DataTable();
            result.Columns.Add(Alias.Rule.ID, MapCSType(Alias.Rule.ID));
            result.Columns.Add(Alias.Rule.InnerID, MapCSType(Alias.Rule.InnerID));
            result.Columns.Add(Alias.Rule.Name, MapCSType(Alias.Rule.Name));
            result.Columns.Add(Alias.Rule.Config, MapCSType(Alias.Rule.Config));
            result.Columns.Add(Alias.Rule.Description, MapCSType(Alias.Rule.Description));
            result.Columns.Add(Alias.Rule.Every, MapCSType(Alias.Rule.Every));
            result.Columns.Add(Alias.Rule.StartTime, MapCSType(Alias.Rule.StartTime));
            result.Columns.Add(Alias.Rule.AutoExport, MapCSType(Alias.Rule.AutoExport));
            result.Columns.Add(Alias.Rule.LastRun, MapCSType(Alias.Rule.LastRun));
            result.Columns.Add(Alias.Rule.RunTimes, MapCSType(Alias.Rule.RunTimes));
            result.Columns.Add(Alias.Rule.EndTime, MapCSType(Alias.Rule.EndTime));
            result.Columns.Add(Alias.Rule.LastID, MapCSType(Alias.Rule.LastID));
            result.Columns.Add(Alias.Rule.UserAgent, MapCSType(Alias.Rule.UserAgent));
            result.Columns.Add(Alias.Rule.IsDeleted, MapCSType(Alias.Rule.IsDeleted));
            result.Columns.Add(Alias.Rule.CreatorID, MapCSType(Alias.Rule.CreatorID));
            result.Columns.Add(Alias.Rule.Creator, MapCSType(Alias.Rule.Creator));
            result.Columns.Add(Alias.Rule.CreateTime, MapCSType(Alias.Rule.CreateTime));
            result.Columns.Add(Alias.Rule.UpdatorID, MapCSType(Alias.Rule.UpdatorID));
            result.Columns.Add(Alias.Rule.Updator, MapCSType(Alias.Rule.Updator));
            result.Columns.Add(Alias.Rule.UpdateTime, MapCSType(Alias.Rule.UpdateTime));

            #region 条件
            Command.Parameters.Clear();
            string parenthesis = String.Empty;
            string join = String.Empty;
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                where.Append(" WHERE " + Alias.Rule.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "a");
            }
            else
            {
                where.Append(" WHERE a." + MapColumn(Alias.Rule.RowLang) + " LIKE '%|" + Lang + "|%'");
            }

            #region HasSelfLimitation
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null && Convert.ToBoolean(user["HasSelfLimitation"]))
                {
                    if (where.Length > 0)
                        where.Append(" AND ");

                    where.Append("a." + MapColumn(Alias.Rule.CreatorID) + "=?");
                    Command.Parameters.Add("@" + Alias.Rule.CreatorID, MapType(Alias.Rule.CreatorID)).Value = new Guid(user["ID"]);
                }
            }
            #endregion

            #endregion

            #region 排序
            if (!String.IsNullOrEmpty(sort))
                sort = " ORDER BY " + ParseSort(sort, "a");
            else
                sort = " ORDER BY a." + MapColumn(Alias.Rule.InnerID) + " DESC";
            #endregion

            #region 构造SQL语句
            StringBuilder sql = new StringBuilder("SELECT");
            if (page > 0 && pageSize > 0)
                sql.Append(" TOP " + (page * pageSize));
            sql.Append(" a." + MapColumn(Alias.Rule.ID));
            sql.Append(",a." + MapColumn(Alias.Rule.InnerID));
            sql.Append(",a." + MapColumn(Alias.Rule.Name, Lang));
            sql.Append(",a." + MapColumn(Alias.Rule.Config));
            sql.Append(",a." + MapColumn(Alias.Rule.Description, Lang));
            sql.Append(",a." + MapColumn(Alias.Rule.Every));
            sql.Append(",a." + MapColumn(Alias.Rule.StartTime));
            sql.Append(",a." + MapColumn(Alias.Rule.AutoExport));
            sql.Append(",a." + MapColumn(Alias.Rule.LastRun));
            sql.Append(",a." + MapColumn(Alias.Rule.RunTimes));
            sql.Append(",a." + MapColumn(Alias.Rule.EndTime));
            sql.Append(",a." + MapColumn(Alias.Rule.LastID));
            sql.Append(",a." + MapColumn(Alias.Rule.UserAgent));
            sql.Append(",a." + MapColumn(Alias.Rule.IsDeleted));
            sql.Append(",a." + MapColumn(Alias.Rule.CreatorID));
            sql.Append(",a." + MapColumn(Alias.Rule.Creator));
            sql.Append(",a." + MapColumn(Alias.Rule.CreateTime));
            sql.Append(",a." + MapColumn(Alias.Rule.UpdatorID));
            sql.Append(",a." + MapColumn(Alias.Rule.Updator));
            sql.Append(",a." + MapColumn(Alias.Rule.UpdateTime));
            sql.Append(" FROM " + parenthesis + MapTable(Alias.Objects.Rule) + " AS a");
            sql.Append(join + where + sort);
            Command.CommandText = sql.ToString();
            #endregion

            #region 执行SQL语句并获取记录
            int curIndex = 0, rowIndex = 0;
            int startIndex = (page - 1) * pageSize;
            DataReader = Command.ExecuteReader();
            while (DataReader.Read())
            {
                if (pageSize != -1)
                {
                    if (curIndex < startIndex)
                    {
                        curIndex++;
                        continue;
                    }

                    if (rowIndex == pageSize)
                        break;
                }

                DataRow row = result.NewRow();
                int i = 0;
                row[Alias.Rule.ID] = DataReader[i++];
                row[Alias.Rule.InnerID] = DataReader[i++];
                row[Alias.Rule.Name] = DataReader[i++];
                row[Alias.Rule.Config] = DataReader[i++];
                row[Alias.Rule.Description] = DataReader[i++];
                row[Alias.Rule.Every] = DataReader[i++];
                row[Alias.Rule.StartTime] = DataReader[i++];
                row[Alias.Rule.AutoExport] = DataReader[i++];
                row[Alias.Rule.LastRun] = DataReader[i++];
                row[Alias.Rule.RunTimes] = DataReader[i++];
                row[Alias.Rule.EndTime] = DataReader[i++];
                row[Alias.Rule.LastID] = DataReader[i++];
                row[Alias.Rule.UserAgent] = DataReader[i++];
                row[Alias.Rule.IsDeleted] = DataReader[i++];
                row[Alias.Rule.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Rule.Creator] = DataReader[i++];
                row[Alias.Rule.CreateTime] = DataReader[i++];
                row[Alias.Rule.UpdatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Rule.Updator] = DataReader[i++];
                row[Alias.Rule.UpdateTime] = DataReader[i++];
                result.Rows.Add(row);

                rowIndex++;
            }
            DataReader.Close();
            #endregion

            return result;
        }
        public int GetRecordCount(string condition)
        {
            #region 条件
            Command.Parameters.Clear();
            string parenthesis = String.Empty;
            string join = String.Empty;
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                where.Append(" WHERE " + Alias.Rule.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "a");
            }
            else
            {
                where.Append(" WHERE a." + MapColumn(Alias.Rule.RowLang) + " LIKE '%|" + Lang + "|%'");
            }

            #region HasSelfLimitation
            if (CheckRight)
            {
                Dictionary<string, string> user = Manager.User;
                if (user != null && Convert.ToBoolean(user["HasSelfLimitation"]))
                {
                    if (where.Length > 0)
                        where.Append(" AND ");

                    where.Append("a." + MapColumn(Alias.Rule.CreatorID) + "=?");
                    Command.Parameters.Add("@" + Alias.Rule.CreatorID, MapType(Alias.Rule.CreatorID)).Value = new Guid(user["ID"]);
                }
            }
            #endregion

            #endregion

            Command.CommandText = "SELECT COUNT(*) FROM " + parenthesis + MapTable(Alias.Objects.Rule) + " AS a" + join + where;
            return Convert.ToInt32(Command.ExecuteScalar());
        }
    }
}
